package com.winit.project.core.edition;

import com.winit.common.util.BAssert;
import com.winit.common.util.ConfigUtil;
import com.winit.project.util.ProjectUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.File;
import java.util.List;

/**
 * Created by wangjian on 16/9/7.
 */
public class EditionCleaner {

    private static final Logger logger = LoggerFactory.getLogger(EditionCleaner.class);

    /**
     * 分支工程目录
     */
    private String path;
    private String qaTestEdition;
    private String projectName;

    public EditionCleaner(String projectName,String qaTestEdition) throws Exception{
        BAssert.isEmpty("删除工程版本,参数存在空值.",logger,projectName);
        this.path = ProjectUtil.getProjectFilePath(projectName);
        this.projectName = projectName;
        this.qaTestEdition = qaTestEdition;
    }

    /**
     * 清空指定的版本所在的文件路径.
     * 用于定期整理以便节省磁盘空间的功能.
     * 版本列表不包括default版本
     * @param editions
     * @return
     * @throws Exception 指定版本的路径不存在,则抛出异常.
     */
    public boolean doClean(List<PackageEdition> editions,String buildDir) throws Exception{
        logger.info("删除工程多余版本.path="+this.path);
        File file = new File(this.path);

        BAssert.isTrue("删除工程多余版本,目录不存在.path="+this.path,file.exists(),logger);
        //1 获取版本数量
        //2 判断是否超过限制
        //3 超过限制后,按时间顺序删除超过的版本
        Integer size = editions.size();
        if(size == 0){
            logger.info("工程已构建版本数为0,projectName="+this.projectName);
            return true;
        }

        Integer count = Integer.valueOf(ConfigUtil.getValue("edition_count_max"));
        if(size < count){
            logger.info("工程已构建版本数未超过限值,size="+size+",projectName="+this.projectName);
            return true;
        }

        Integer delCount = size - count + 1;
        for (int i=size-1;i>0;i--){
            if(delCount <= 0){
                break;
            }
            PackageEdition edition = editions.get(i);
            try {
                edition.removeEdition(this.qaTestEdition,buildDir);
                delCount--;
            }catch (Exception e){
                String path= edition!=null? edition.getPath():"edition对象为null";
                logger.error("尝试删除工程,但发生异常,Path="+path+"errorMsg:"+e.getMessage());
            }
        }
        return true;
    }

    public String getPath() {
        return path;
    }

}
